package com.mrdeer.iot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mrdeer.common.JSONResult;
import com.mrdeer.iot.dto.ShopEntityDTO;
import com.mrdeer.iot.entity.ShopEntity;
import com.mrdeer.iot.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 店铺接口
 *
 * @Author: xie jianchu
 */
@Slf4j
@RestController
@RequestMapping("/mrdeer/shop")
@Api(value = "店铺管理接口", tags = "店铺管理业务")
public class ShopController {

    @Resource
    private ShopService shopService;

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public JSONResult getAll() {
        List<ShopEntity> list = shopService.list();
        return JSONResult.ok(list);
    }

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public JSONResult get(@PathVariable String id) {
        ShopEntity shopEntity = shopService.getById(id);
        return JSONResult.ok(shopEntity);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiOperation(value = "多条件分页获取用户列表")
    public JSONResult getByCondition(@RequestBody ShopEntityDTO dto) {
        try {
            Page<ShopEntity> page = shopService.list(dto);
            if (null != page) {
                return JSONResult.ok(page);
            }
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
        return JSONResult.errorMsg("error");
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加")
    public JSONResult add(@RequestBody ShopEntity shop) {
        if (shopService.getOne(new QueryWrapper<ShopEntity>().eq("shop_name", shop.getShopName())) != null) {
            return JSONResult.errorMsg("店铺已经存在");
        }
        shopService.save(shop);
        return JSONResult.ok("添加成功");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "编辑店铺")
    public JSONResult edit(@RequestBody ShopEntity shopEntity) {
        shopService.update(shopEntity, new LambdaQueryWrapper<ShopEntity>().eq(ShopEntity::getId, shopEntity.getId()));
        return JSONResult.ok("编辑成功");
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "批量删除店铺")
    public JSONResult delShops(@RequestParam String ids) {
        String[] idsArr = ids.split(",");
        for (String id : idsArr) {
            //TODO:
            shopService.delete(id);
        }
        return JSONResult.ok("删除成功");
    }

}
